import {StyleSheet, Text, TouchableOpacity, View, Image} from 'react-native'
import React, {useEffect, useState, useRef} from 'react'
import PageScrollView from "@/components/PageScrollView";
import FcButton from "@/components/FcButton";
import {Video} from 'expo-av';
import {StatusBar} from "expo-status-bar";
import {router, useLocalSearchParams} from "expo-router";
import {Toast, Flex} from "@ant-design/react-native";
import {useDispatch, useSelector} from "react-redux";
import {set_videoList} from "@/store/reducer/videoPublish/videoPublishSlice";
import * as VideoThumbnails from 'expo-video-thumbnails';
import * as ImagePicker from "expo-image-picker";

import {
  useVideoUploadMutation,
} from "@/store/api/videoPublish/videoPublishApi";

type Props = {}

const editCover = (props: Props) => {
  const [pageScrollBodyH, setPageScrollBodyH] = useState(0)
  const [videoList, setVideoList] = useState<any>({})
  const [videoItem, setVideoItem] = useState<any>({})
  const [activeTab, setActiveTab] = useState(1)
  const [videoDuration, setVideoDuration] = useState<any>('00:01')

  const videoRef = useRef<any>(null);

  const [videoUploadFun] = useVideoUploadMutation()

  const dispatch = useDispatch()
  const {id} = useLocalSearchParams()

  let p = useSelector(state => state.videoPublish.videoList)

  useEffect(() => {
    let obj = p.find((val:any) => val.id == id)
    console.log("sssss", obj, id, p)
    setVideoItem(obj)
    setVideoList(p)
  },[p, id])

  const getScrollBodyInfo = ({height}) => {
    setPageScrollBodyH(height)
  }

  const handleTab = (val:any) => {
    setActiveTab(val)

    if(val == 2){
      uploadFile()
    }
  }

  //获取封面
  const handleCurrentDuration = async() => {
    const status = await videoRef.current.getStatusAsync();

    await videoRef.current.pauseAsync()

    const { uri: thumbnailUri } = await VideoThumbnails?.getThumbnailAsync(
      videoItem?.fileInfo?.uri,
      {
        time: status.positionMillis,
      }
    );

    let positionMillis = status.positionMillis / 1000;
    let minutes = Math.floor(positionMillis / 60).toString().padStart(2, '0');
    let seconds = Math.floor((positionMillis % 60).toString().padStart(2, '0'));
    let duration = `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;

    setVideoItem({
      ...videoItem,
      coverTsp: positionMillis,
      temporaryCover: thumbnailUri,
      coverImagePath: '',
    })

    setVideoDuration(duration)

    let arr = JSON.parse(JSON.stringify(videoList))
    let index = arr.findIndex((val:any) => val.id === videoItem.id)
    arr[index] = {
      ...arr[index],
      coverTsp: positionMillis,
      temporaryCover: thumbnailUri,
      coverImagePath: '',
    }
    dispatch(set_videoList(arr))

    Toast.info('封面设置成功')
  }

  //上传图片
  async function uploadFile() {
    let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();

    if (permissionResult.granted === false) {
      alert('Permission to access gallery is required!');
      return;
    }

    let pickerResult = await ImagePicker.launchImageLibraryAsync({
      allowsMultipleSelection: false, //可以在相册中选择多个
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: false, // 可选，允许用户编辑所选图片或视频。
      quality: 1, // 可选，设置图片或视频的质量。0到1之间。1表示最高质量。
    });

    if (!pickerResult.canceled) {
      const formData = new FormData();

      formData.append('biz', 'jeditor');
      formData.append('jeditor', '1');
      formData.append('file', {
        uri: pickerResult?.assets[0].uri,
        name: pickerResult?.assets[0].fileName,
        type: 'image/jpeg',
      });

      videoUploadFun(formData).then(res => {
        setVideoItem({
          ...videoItem,
          coverImagePath: res.data.result.path,
          temporaryCover: pickerResult?.assets[0].uri
        })
        Toast.info('封面设置成功')

        let arr = JSON.parse(JSON.stringify(videoList))
        let index = arr.findIndex((val:any) => val.id === videoItem.id)
        arr[index] = {
          ...arr[index],
          coverImagePath: res.data.result.path,
          temporaryCover: pickerResult?.assets[0].uri
        }
        dispatch(set_videoList(arr))
      })
    }
  }

  //裁剪封面
  const handleCropImage = async() => {
    
  }

  return (
    <View style={{flex: 1, backgroundColor: '#000', paddingHorizontal: 16}}>
      <StatusBar style='light'></StatusBar>
      <PageScrollView
        themedStyle={{backgroundColor: 'transparent'}}
        getPageScrollBodyInfo={getScrollBodyInfo}
        bodyStyle={{padding: 0}}
        isTransparentTab
        pageTab={
          <Flex justify='between' style={{height: 44}}>
            <TouchableOpacity onPress={() => router.back()}>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 24, color: '#FFF', marginRight: 3}}>&#xe659;</Text>
            </TouchableOpacity>

            <Flex>
              <TouchableOpacity onPress={() => handleTab(1)} style={{marginRight: 24}}>
                <Text style={[{fontSize: 15}, {color: activeTab === 1 ? '#6989FF' : '#FFF'}]}>从视频中选取</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => handleTab(2)}>
                <Text style={[{fontSize: 15}, {color: activeTab === 2 ? '#6989FF' : '#FFF'}]}>从相册选取</Text>
              </TouchableOpacity>
            </Flex>
            
            <FcButton
              onClick={() => router.back()}
              type='BjJB'
              colors={['#6989FF', '#C65EFD']}
              style={{width: 52, height: 32}}
              itemStyle={{borderRadius: 8}}
              textName='完成'
            />
          </Flex>
        }
        pageBottom={
          activeTab == 1 ?
          <Flex justify='between' style={{height: 72}}>
            <Flex>
              <Image style={{width: 30, height: 46, borderRadius: 4, marginRight: 10}} resizeMode={'cover'} source={{uri: videoItem.temporaryCover}}></Image>
              {videoDuration && <Text style={{color: '#9E9E9E'}}>已选取<Text style={{color: '#FFF'}}>{videoDuration}</Text></Text>}
            </Flex>

            <Flex>
              <FcButton
                onClick={() => handleCurrentDuration()}
                type='BjJB'
                colors={['rgba(105, 137, 255, 0.2)', 'rgba(198, 94, 253, 0.2)']}
                style={{width: 94, height: 38, justifyContent: 'center', marginRight: 10}}
                itemStyle={{borderRadius: 8}}
                textName='设置封面'
              />
              <FcButton
                onClick={() => handleCropImage()}
                type='BjJB'
                colors={['rgba(105, 137, 255, 0.2)', 'rgba(198, 94, 253, 0.2)']}
                style={{width: 94, height: 38, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8}}
                textName='编辑封面'
              />
            </Flex>
          </Flex>
          :
          <Flex justify='center' style={{height: 72}}>
            <FcButton
              onClick={() => handleCropImage()}
              type='BjJB'
              colors={['rgba(105, 137, 255, 0.2)', 'rgba(198, 94, 253, 0.2)']}
              style={{width: 94, height: 38, justifyContent: 'center'}}
              itemStyle={{borderRadius: 8}}
              textName='编辑封面'
            />
          </Flex>
        }
      >
        <View style={{height: pageScrollBodyH}}>
          {
            activeTab == 1 ?
            <Video
              ref={videoRef}
              style={{ width: '100%', height: '100%' }}
              source={{ uri: videoItem?.fileInfo?.uri }} // 视频 URL
              useNativeControls
              resizeMode="cover"
              isLooping={false}
            />
            :
            <Image style={{width: '100%', height: '100%'}} resizeMode={'contain'} source={{uri: videoItem.temporaryCover}}></Image>
          }
        </View>
      </PageScrollView>
    </View>
  )
}

export default editCover

const styles = StyleSheet.create({
  
})